﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FunnyFunction
{
    public class GuessFlower
    {
        public  int[,] Arr;
        private int X;
        public int Count;
        public GuessFlower(int X, int Count)
        {
            this.X = X;
            this.Arr = new int[X, X];
            this.Count = Count;

            Init();
        }

        public void Show()
        {
            for (int y = 0; y < X; y++)
            {
                for (int x = 0; x < X; x++)
                {
                    if (Arr[x, y] == 0)
                        Console.Write("  ");
                    else
                        Console.Write("O");
                }
                Console.WriteLine("");
            }
        }

        private void Init()
        {
            Random rand = new Random();
            var max = this.X * this.X;
            List<int> SelectList = new List<int>();
            for (int i = 0; i < max; i++)
            {
                SelectList.Add(i);
            }
            List<int> sList = new List<int>();
            for (int i = 0; i < Count; i++)
            {
                if (SelectList.Count <= 0)
                    throw new Exception("生成错误！");

                var index = SelectList[rand.Next(0, SelectList.Count)];

                var x = index % X;
                var y = index / X;
                Arr[x, y] = 1;
                sList.Add(index);
                SelectList.Remove(index);

                var cList = GetCrossList(x, y);
                if (cList.Any(t => sList.Contains(t)))
                {
                    if (sList.Count < this.Count / 2)
                    {
                        i--;
                        continue;
                    }    
                    SelectList.RemoveAll(t => cList.Contains(t));
                }
            }
        }

        private List<int> GetCrossList(int x, int y)
        {
            List<int> list = new List<int>();
            for (int i = 0; i < X; i++)
            {
                list.Add(X * i + x);
                list.Add(y * X + i);
            }
            list.RemoveAll(t => t == (y * X + x));

            return list;
        }
    }
}
